import sys
import os
import yaml
from typing import Dict, List, Any, Optional
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QLabel, QLineEdit, QRadioButton, QCheckBox, QPushButton,
                             QGroupBox, QScrollArea, QMessageBox, QButtonGroup, QGridLayout,
                             QFrame, QSpacerItem, QSizePolicy)
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QFont, QPalette, QColor


class Hero:
    def __init__(self):
        self.phy = ""
        self.mag = ""
        self.loop = 0
        self.stat = None
        self.skills = []


class Stat:
    def __init__(self):
        self.hp = 0
        self.ar = 0
        self.dr = 0
        self.heal = 0
        self.shield = 0
        self.recover = 0


class MineYamlEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        # field_mappings 保持上一版本 (stackMode 合并, buff/buffDur 拆分)
        self.field_mappings = {
            "initMana": {"display": "初始蓝量", "placeholder": "可选，缺省则默认为0"},
            "mana": {"display": "施法蓝量", "placeholder": "可选，蓝条。例如 100"},
            "d1": {"display": "主要伤害", "placeholder": "主要伤害值，支持表达式。例如 100、2.0*ad"},
            "d1Pre": {"display": "施法前摇", "placeholder": "施法前摇（以100ms为单位）。例如 15 => 施法前摇1.5秒"},
            "d2": {"display": "次要伤害", "placeholder": "次要伤害（可选）物理技能的AP加成部分"},
            "grow": {"display": "最大生命值增长", "placeholder": "可选，支持表达式。如100、100*ap+10*hp"},
            "heal": {"display": "治疗量", "placeholder": "可选，支持表达式。如100、100*ap+10*hp"},
            "stackDamage": {"display": "叠加伤害", "placeholder": "叠加伤害。例如 100 => 每层叠加伤害为100"},
            "stackMode": {"display": "叠加方式", "placeholder": "叠层阈值，例如5"},
            "buff": {"display": "增益效果", "placeholder": "加100法强，ap_100"},
            "buffDur": {"display": "增益持续时间", "placeholder": "秒/攻击次数"},
            "shield": {"display": "护盾量", "placeholder": "可选，支持表达式。如100、100*ap+10*hp"},
            "shieldDur": {"display": "护盾持续时间", "placeholder": "可选，若空默认为2秒"}
        }

        self.stack_mode_map = {
            "施法次数": "cast",
            "额外攻速": "as",
            "攻击次数": "atk",
        }

        # --- NEW: 增益持续时间类型映射 ---
        self.dur_type_map = {
            "秒": "time",
            "攻击次数": "atk"
        }

        self.skill_widgets = []
        self.init_ui()
        self.apply_dark_theme()

    def init_ui(self):
        self.setWindowTitle("英雄编辑器")
        self.setGeometry(100, 100, 900, 1000)

        # 创建中央部件和主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.NoFrame)
        scroll_content = QWidget()
        main_layout = QVBoxLayout(scroll_content)
        main_layout.setSpacing(12)
        main_layout.setContentsMargins(20, 20, 20, 20)

        # 添加标题
        title_label = QLabel("英雄编辑器")
        title_font = QFont()
        title_font.setPointSize(20)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("color: white; padding: 15px;")
        main_layout.addWidget(title_label)

        # 添加各个部分
        self.create_hero_section(main_layout)
        self.create_defense_section(main_layout)
        self.create_skills_section(main_layout)
        self.create_save_section(main_layout)

        scroll_area.setWidget(scroll_content)
        self.setCentralWidget(scroll_area)

        # 默认添加一个技能
        self.add_skill_widget()

    def create_hero_section(self, layout):
        group = QGroupBox("英雄基础信息")
        group_font = QFont()
        group_font.setPointSize(14)
        group_font.setBold(True)
        group.setFont(group_font)

        grid_layout = QGridLayout()
        grid_layout.setVerticalSpacing(12)
        grid_layout.setHorizontalSpacing(15)

        # 创建大字体
        label_font = QFont()
        label_font.setPointSize(12)

        input_font = QFont()
        input_font.setPointSize(11)

        # 英雄名称
        name_label = QLabel("名称:")
        name_label.setFont(label_font)
        grid_layout.addWidget(name_label, 0, 0)

        self.name_entry = QLineEdit()
        self.name_entry.setPlaceholderText("英雄名，例如 Lux")
        self.name_entry.setFont(input_font)
        grid_layout.addWidget(self.name_entry, 0, 1)

        # 伤害类型
        type_label = QLabel("伤害类型:")
        type_label.setFont(label_font)
        grid_layout.addWidget(type_label, 1, 0)

        self.damage_type_group = QButtonGroup(self)
        self.phy_radio = QRadioButton("物理 (Phy)")
        self.mag_radio = QRadioButton("魔法 (Mag)")
        self.mag_radio.setChecked(True)
        self.damage_type_group.addButton(self.phy_radio)
        self.damage_type_group.addButton(self.mag_radio)

        # 设置单选按钮字体
        radio_font = QFont()
        radio_font.setPointSize(11)
        self.phy_radio.setFont(radio_font)
        self.mag_radio.setFont(radio_font)

        type_layout = QHBoxLayout()
        type_layout.addWidget(self.phy_radio)
        type_layout.addWidget(self.mag_radio)
        type_layout.addStretch(1)
        type_widget = QWidget()
        type_widget.setLayout(type_layout)
        grid_layout.addWidget(type_widget, 1, 1)

        # 基础攻击力
        damage_label = QLabel("基础攻击力:")
        damage_label.setFont(label_font)
        grid_layout.addWidget(damage_label, 2, 0)

        self.damage_entry = QLineEdit()
        self.damage_entry.setPlaceholderText("例如 60")
        self.damage_entry.setFont(input_font)
        grid_layout.addWidget(self.damage_entry, 2, 1)

        # 基础攻速
        speed_label = QLabel("基础攻速:")
        speed_label.setFont(label_font)
        grid_layout.addWidget(speed_label, 3, 0)

        self.speed_entry = QLineEdit()
        self.speed_entry.setPlaceholderText("默认0.75")
        self.speed_entry.setText("0.75")
        self.speed_entry.setFont(input_font)
        grid_layout.addWidget(self.speed_entry, 3, 1)

        group.setLayout(grid_layout)
        layout.addWidget(group)

    def create_defense_section(self, layout):
        group = QGroupBox("防御属性 (可选)")
        group_font = QFont()
        group_font.setPointSize(14)
        group_font.setBold(True)
        group.setFont(group_font)

        grid_layout = QGridLayout()
        grid_layout.setVerticalSpacing(12)
        grid_layout.setHorizontalSpacing(15)

        # 创建大字体
        label_font = QFont()
        label_font.setPointSize(12)

        input_font = QFont()
        input_font.setPointSize(11)

        # 防御属性字段
        defenses = [
            ("血量", "hp_entry", "为空则不计算自我缓和伤害"),
            ("双抗", "ar_entry", "护甲"),
            ("减伤", "dr_entry", "减伤"),
            ("治疗增幅", "heal_entry", "绝大部分英雄可省略"),
            ("护盾增幅", "shield_entry", "绝大部分英雄可省略"),
            ("治疗+护盾增幅", "recover_entry", "治疗+护盾增幅")
        ]

        for i, (label, attr, placeholder) in enumerate(defenses):
            label_widget = QLabel(f"{label}:")
            label_widget.setFont(label_font)
            grid_layout.addWidget(label_widget, i, 0)

            entry = QLineEdit()
            entry.setPlaceholderText(placeholder)
            entry.setFont(input_font)
            setattr(self, attr, entry)
            grid_layout.addWidget(entry, i, 1)

        group.setLayout(grid_layout)
        layout.addWidget(group)

    def create_skills_section(self, layout):
        group = QGroupBox("技能设置")
        group_font = QFont()
        group_font.setPointSize(14)
        group_font.setBold(True)
        group.setFont(group_font)

        v_layout = QVBoxLayout()
        v_layout.setSpacing(12)

        # 创建大字体
        checkbox_font = QFont()
        checkbox_font.setPointSize(12)

        button_font = QFont()
        button_font.setPointSize(11)

        # 循环施法
        self.loop_check = QCheckBox("循环施法")
        self.loop_check.setFont(checkbox_font)
        v_layout.addWidget(self.loop_check)

        # 添加技能按钮
        add_btn = QPushButton("添加技能")
        add_btn.setFont(button_font)
        add_btn.clicked.connect(self.add_skill_widget)
        v_layout.addWidget(add_btn)

        # 技能容器
        self.skills_container = QVBoxLayout()
        self.skills_container.setSpacing(10)
        v_layout.addLayout(self.skills_container)

        group.setLayout(v_layout)
        layout.addWidget(group)

    def create_save_section(self, layout):
        # 创建大字体
        button_font = QFont()
        button_font.setPointSize(14)
        button_font.setBold(True)

        status_font = QFont()
        status_font.setPointSize(12)

        # 按钮布局
        button_layout = QHBoxLayout()

        # 保存按钮
        save_btn = QPushButton("完成编辑")
        save_btn.setFont(button_font)
        save_btn.clicked.connect(self.save_to_yaml)
        # layout.addWidget(save_btn)
        button_layout.addWidget(save_btn)

        # 重置按钮
        reset_btn = QPushButton("重置默认值")
        reset_btn.setFont(button_font)
        reset_btn.clicked.connect(self.reset_to_default)
        reset_btn.setStyleSheet("background-color: #444;")
        button_layout.addWidget(reset_btn)

        layout.addLayout(button_layout)

        # 状态标签
        self.status_label = QLabel("准备就绪")
        self.status_label.setFont(status_font)
        self.status_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.status_label)

    def add_skill_widget(self):
        skill_widget = QGroupBox(f"技能 #{len(self.skill_widgets) + 1}")
        skill_font = QFont()
        skill_font.setPointSize(13)
        skill_font.setBold(True)
        skill_widget.setFont(skill_font)

        skill_layout = QGridLayout()
        skill_layout.setVerticalSpacing(8)
        skill_layout.setHorizontalSpacing(10)

        # 创建大字体
        label_font = QFont()
        label_font.setPointSize(11)

        input_font = QFont()
        input_font.setPointSize(10)

        radio_font = QFont()
        radio_font.setPointSize(10)

        check_font = QFont()
        check_font.setPointSize(10)

        button_font = QFont()
        button_font.setPointSize(10)

        fields = {}

        row = 0
        for key, config in self.field_mappings.items():
            label = QLabel(f"{config['display']}:")
            label.setFont(label_font)
            skill_layout.addWidget(label, row, 0)

            # --- MODIFIED: stackMode 的 UI (不变) ---
            if key == "stackMode":
                entry = QLineEdit()
                entry.setFont(input_font)
                entry.setPlaceholderText(config["placeholder"])
                entry.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

                mode_group = QButtonGroup(skill_widget)
                mode_radios = []
                for mode_text in ["施法次数", "额外攻速", "攻击次数"]:
                    radio = QRadioButton(mode_text)
                    radio.setFont(radio_font)
                    mode_group.addButton(radio)
                    mode_radios.append(radio)

                if mode_radios:
                    mode_radios[0].setChecked(True)

                h_layout = QHBoxLayout()
                h_layout.setContentsMargins(0, 0, 0, 0)
                h_layout.addWidget(entry)
                for radio in mode_radios:
                    h_layout.addWidget(radio)
                h_layout.addStretch(1)

                h_widget = QWidget()
                h_widget.setLayout(h_layout)

                skill_layout.addWidget(h_widget, row, 1)

                fields["stackThreshold"] = entry
                fields["stackMode"] = mode_group

            # --- MODIFIED: 重写 buff 的 UI 为 (LineEdit + CheckBox + CheckBox) ---
            elif key == "buff":
                # 1. 创建 "增益效果" 输入框
                effect_entry = QLineEdit()
                effect_entry.setFont(input_font)
                effect_entry.setPlaceholderText(config["placeholder"])
                effect_entry.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

                # 2. 创建 "法力锁" 复选框
                mana_lock_check = QCheckBox("法力锁")
                mana_lock_check.setFont(check_font)
                mana_lock_check.setChecked(True)  # 默认勾选

                # 3. 创建 "可叠加" 复选框
                stackable_check = QCheckBox("可叠加")
                stackable_check.setFont(check_font)
                stackable_check.setChecked(False)  # 默认不勾选

                # 4. 将输入框和复选框放入一个水平布局
                h_layout = QHBoxLayout()
                h_layout.setContentsMargins(0, 0, 0, 0)
                h_layout.addWidget(effect_entry)  # 效果输入框 (ap_100)
                h_layout.addWidget(mana_lock_check)
                h_layout.addWidget(stackable_check)
                h_layout.addStretch(1)  # 确保它们靠左

                h_widget = QWidget()
                h_widget.setLayout(h_layout)

                # 5. 将整个布局添加到网格
                skill_layout.addWidget(h_widget, row, 1)

                # 6. 存储控件
                fields[key] = effect_entry  # "buff" 键存储 QLineEdit
                fields["buff_mana_lock"] = mana_lock_check
                fields["buff_stackable"] = stackable_check

            # --- END MODIFIED ---

            # --- MODIFIED: buffDur 的 UI (修改显示文本和顺序) ---
            elif key == "buffDur":
                # 1. 创建持续时间输入框
                entry = QLineEdit()
                entry.setFont(input_font)
                entry.setPlaceholderText(config["placeholder"])
                entry.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

                # 2. 创建持续时间类型单选按钮
                dur_type_group = QButtonGroup(skill_widget)

                # 定义新的显示文本和顺序
                time_radio = QRadioButton("秒") # 修改显示文本
                time_radio.setFont(radio_font)
                time_radio.setChecked(True)

                atk_radio = QRadioButton("攻击次数") # 修改显示文本
                atk_radio.setFont(radio_font)

                dur_type_group.addButton(time_radio)
                dur_type_group.addButton(atk_radio)

                # 3. 将输入框和单选框放入一个水平布局
                dur_layout = QHBoxLayout()
                dur_layout.setContentsMargins(0, 0, 0, 0)
                dur_layout.addWidget(entry)
                dur_layout.addWidget(time_radio) # "秒" 排在前面
                dur_layout.addWidget(atk_radio) # "攻击次数" 排在后面
                dur_layout.addStretch(1)

                dur_widget = QWidget()
                dur_widget.setLayout(dur_layout)

                # 4. 将整个布局添加到网格
                skill_layout.addWidget(dur_widget, row, 1)

                # 5. 存储控件
                fields[key] = entry
                fields["buff_dur_type"] = dur_type_group
            # --- END MODIFIED ---

            else:
                # 其他字段使用输入框
                entry = QLineEdit()
                entry.setFont(input_font)
                if config["placeholder"]:
                    entry.setPlaceholderText(config["placeholder"])
                skill_layout.addWidget(entry, row, 1)
                fields[key] = entry

            row += 1

        # 删除按钮
        delete_btn = QPushButton("删除技能")
        delete_btn.setFont(button_font)
        delete_btn.clicked.connect(lambda: self.delete_skill_widget(skill_widget))
        skill_layout.addWidget(delete_btn, row, 0, 1, 2)

        skill_widget.setLayout(skill_layout)
        self.skills_container.addWidget(skill_widget)

        self.skill_widgets.append({
            "widget": skill_widget,
            "fields": fields
        })

    def delete_skill_widget(self, skill_widget):
        for i, sw in enumerate(self.skill_widgets):
            if sw["widget"] == skill_widget:
                sw["widget"].deleteLater()
                self.skill_widgets.pop(i)
                break

        # 更新剩余技能的标题
        for i, sw in enumerate(self.skill_widgets):
            sw["widget"].setTitle(f"技能 #{i + 1}")

    def collect_skill_data(self, skill_fields):
        skill = {}

        # 处理D1和前摇
        d1_val = skill_fields["d1"].text().strip()
        d1_pre_val = skill_fields["d1Pre"].text().strip()

        if d1_val and d1_pre_val:
            skill["d1"] = f"{d1_val} | {d1_pre_val}"
        elif d1_val:
            skill["d1"] = d1_val

        # 处理 stack 数据 (不变)
        stack_damage_val = skill_fields["stackDamage"].text().strip()
        stack_threshold_val = skill_fields["stackThreshold"].text().strip()

        stack_mode_val = ""
        if "stackMode" in skill_fields:
            for btn in skill_fields["stackMode"].buttons():
                if btn.isChecked():
                    stack_mode_val = btn.text()
                    break

        if stack_damage_val and stack_mode_val and stack_threshold_val:
            actual_mode = self.stack_mode_map.get(stack_mode_val, stack_mode_val)
            skill["stack"] = f"{stack_damage_val}, {stack_threshold_val} {actual_mode}"
        elif stack_mode_val:
            actual_mode = self.stack_mode_map.get(stack_mode_val, stack_mode_val)
            if stack_threshold_val:
                skill["stack"] = f", {stack_threshold_val} {actual_mode}"
            else:
                skill["stack"] = actual_mode

        # 处理护盾和持续时间 (不变)
        shield_val = skill_fields["shield"].text().strip()
        shield_dur_val = skill_fields["shieldDur"].text().strip()

        if shield_val:
            dur = shield_dur_val if shield_dur_val else "2"
            skill["shield"] = f"{shield_val}, {dur}"

        # --- MODIFIED: 收集 Buff 数据 (改回收 QCheckBox) ---
        buff_val = skill_fields["buff"].text().strip()
        buff_dur_val = skill_fields["buffDur"].text().strip()

        if buff_val:
            buff_parts = [buff_val]  # e.g., ["ap_100"]

            # 1. 检查法力锁: 默认勾选 (有锁), 如果 *未勾选*, 才添加 "free"
            if not skill_fields["buff_mana_lock"].isChecked():
                buff_parts.append("free")

            # 2. 检查可叠加: 默认不勾选 (刷新), 如果 *已勾选*, 才添加 "dup"
            if skill_fields["buff_stackable"].isChecked():
                buff_parts.append("dup")

            # 3. 组合字符串
            final_buff_str = " ".join(buff_parts)

            # 4. 添加持续时间
            # --- MODIFIED: 收集 buffDur 数据 (使用映射) ---
            if buff_dur_val:
                dur_type = "time" # 默认值 (对应 "秒")
                for btn in skill_fields["buff_dur_type"].buttons():
                    if btn.isChecked():
                        display_text = btn.text() # 读取 "秒" 或 "攻击次数"
                        # 使用映射表转回 YAML 所需的值
                        dur_type = self.dur_type_map.get(display_text, "time")
                        break
                final_buff_str += f", {buff_dur_val} {dur_type}"
            # --- END MODIFIED ---
        # --- END MODIFIED ---

        # 处理其他字段
        for key, field in skill_fields.items():
            # --- MODIFIED: 更新跳过列表 ---
            if key in ["d1", "d1Pre",
                       "stackDamage", "stackThreshold", "stackMode",
                       "shield", "shieldDur",
                       "buff", "buffDur", "buff_mana_lock", "buff_stackable", "buff_dur_type"]:
                continue
            # --- END MODIFIED ---

            if isinstance(field, QLineEdit):
                val = field.text().strip()
                if val:
                    skill[key] = val

        return skill

    def apply_dark_theme(self):
        """应用纯黑主题"""
        # (调色板部分不变)
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(0, 0, 0))
        palette.setColor(QPalette.WindowText, QColor(255, 255, 255))
        palette.setColor(QPalette.Base, QColor(25, 25, 25))
        palette.setColor(QPalette.AlternateBase, QColor(35, 35, 35))
        palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 255))
        palette.setColor(QPalette.ToolTipText, QColor(255, 255, 255))
        palette.setColor(QPalette.Text, QColor(255, 255, 255))
        palette.setColor(QPalette.Button, QColor(50, 50, 50))
        palette.setColor(QPalette.ButtonText, QColor(255, 255, 255))
        palette.setColor(QPalette.BrightText, QColor(255, 0, 0))
        palette.setColor(QPalette.Highlight, QColor(100, 100, 100))
        palette.setColor(QPalette.HighlightedText, QColor(255, 255, 255))
        QApplication.setPalette(palette)

        # 设置样式表
        style = """
        QMainWindow {
            background-color: black;
        }
        
        QGroupBox {
            font-weight: bold;
            border: 1px solid #333;
            border-radius: 4px;
            margin-top: 10px;
            padding-top: 10px;
            color: white;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
            color: white;
        }
        
        QLabel {
            color: white;
        }
        
        QLineEdit {
            background-color: #111;
            border: 1px solid #333;
            border-radius: 2px;
            padding: 8px;
            color: white;
            selection-background-color: #444;
        }
        
        QLineEdit:focus {
            border: 1px solid #555;
        }
        
        QPushButton {
            background-color: #222;
            color: white;
            border: 1px solid #333;
            border-radius: 3px;
            padding: 10px 15px;
        }
        
        QPushButton:hover {
            background-color: #333;
            border: 1px solid #444;
        }
        
        QPushButton:pressed {
            background-color: #111;
        }
        
        QRadioButton {
            color: white;
        }
        
        QRadioButton::indicator {
            width: 16px;
            height: 16px;
            border-radius: 8px;
            border: 1px solid #555;
            background-color: #111;
        }
        
        QRadioButton::indicator:checked {
            background-color: #777;
            border: 1px solid #888;
        }
        
        QCheckBox {
            color: white;
        }
        
        QCheckBox::indicator {
            width: 16px;
            height: 16px;
            border: 1px solid #555;
            background-color: #111;
            border-radius: 2px; 
        }
        
        /* --- "打钩" 样式 (不变) --- */
        QCheckBox::indicator:checked {
            background-color: #777;
            border: 1px solid #888;
            image: url();
        }
        
        QScrollArea {
            border: none;
            background-color: black;
        }
        
        QMessageBox {
            background-color: black;
            color: white;
        }
        
        QMessageBox QLabel {
            color: white;
        }
        
        QMessageBox QPushButton {
            background-color: #222;
            color: white;
            border: 1px solid #333;
            border-radius: 3px;
            padding: 8px 15px;
            min-width: 80px;
        }
        """

        self.setStyleSheet(style)

    @pyqtSlot()
    def save_to_yaml(self):
        try:
            # (save_to_yaml 剩余代码不变)

            hero_name = self.name_entry.text().strip()
            if not hero_name:
                QMessageBox.critical(self, "错误", "英雄名不能为空")
                return

            hero = Hero()

            damage_val = self.damage_entry.text().strip() or "0"
            speed_val = self.speed_entry.text().strip() or "0.75"

            if self.phy_radio.isChecked():
                hero.phy = f"{damage_val} {speed_val}"
            else:
                hero.mag = f"{damage_val} {speed_val}"

            if self.loop_check.isChecked():
                hero.loop = 1

            stat = Stat()

            hp_val = self.hp_entry.text().strip()
            if hp_val and hp_val != "为空则不计算自我缓和伤害":
                try:
                    stat.hp = int(hp_val)
                except ValueError:
                    pass

            defense_entries = {
                "ar": self.ar_entry,
                "dr": self.dr_entry,
                "heal": self.heal_entry,
                "shield": self.shield_entry,
                "recover": self.recover_entry
            }

            for field, entry in defense_entries.items():
                val = entry.text().strip()
                if val and not val.endswith("可省略") and not val.endswith("增幅"):
                    try:
                        setattr(stat, field, int(val))
                    except ValueError:
                        pass

            if stat.hp > 0 or stat.ar > 0 or stat.dr > 0 or stat.heal > 0 or stat.shield > 0 or stat.recover > 0:
                hero.stat = stat

            for sw in self.skill_widgets:
                skill_data = self.collect_skill_data(sw["fields"])
                if skill_data:
                    hero.skills.append(skill_data)

            hero_dict = {}
            if hero.phy:
                hero_dict["Phy"] = hero.phy
            if hero.mag:
                hero_dict["Mag"] = hero.mag
            if hero.loop:
                hero_dict["Loop"] = hero.loop
            if hero.stat and any(
                    getattr(hero.stat, attr, 0) for attr in ["hp", "ar", "dr", "heal", "shield", "recover"]):
                stat_dict = {}
                for attr in ["hp", "ar", "dr", "heal", "shield", "recover"]:
                    val = getattr(hero.stat, attr, 0)
                    if val:
                        stat_dict[attr.capitalize()] = val
                if stat_dict:  # 确保字典不为空
                    hero_dict["Stat"] = stat_dict
            if hero.skills:
                hero_dict["Skills"] = hero.skills

            data = {}
            if os.path.exists("mine.yaml"):
                with open("mine.yaml", "r", encoding="utf-8") as f:
                    loaded_data = yaml.safe_load(f)
                    if loaded_data:
                        data = loaded_data

            data[hero_name] = hero_dict

            with open("mine.yaml", "w", encoding="utf-8") as f:
                yaml.dump(data, f, allow_unicode=True, default_flow_style=False)

            self.status_label.setText("✅ 已成功写入 mine.yaml")
            QMessageBox.information(self, "成功", "数据已成功保存到 mine.yaml 文件")

        except Exception as e:
            self.status_label.setText(f"❌ 写入失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"保存文件时出错: {str(e)}")

    @pyqtSlot()
    def reset_to_default(self):
        """重置所有字段为默认值"""
        # (reset_to_default 剩余代码不变)
        self.name_entry.clear()
        self.mag_radio.setChecked(True)
        self.damage_entry.clear()
        self.speed_entry.setText("0.75")

        self.hp_entry.clear()
        self.ar_entry.clear()
        self.dr_entry.clear()
        self.heal_entry.clear()
        self.shield_entry.clear()
        self.recover_entry.clear()

        self.loop_check.setChecked(False)

        for sw in self.skill_widgets:
            sw["widget"].deleteLater()
        self.skill_widgets.clear()
        self.add_skill_widget()

        self.status_label.setText("已重置为默认值")


def main():
    app = QApplication(sys.argv)

    app.setApplicationName("英雄编辑器")
    app.setApplicationVersion("1.0")

    editor = MineYamlEditor()
    editor.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
